package com.ray.auth.login.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ray.auth.system.emun.ManagerType;
import com.ray.auth.system.emun.UserType;
import com.ray.auth.system.service.MenuService;
import com.ray.auth.system.service.NoticeService;
import com.ray.auth.system.service.OrganizationService;
import com.ray.auth.system.service.UserService;
import com.ray.auth.system.service.WorkService;
import com.ray.auth.system.table.entity.Notice;
import com.ray.auth.system.table.entity.Organization;
import com.ray.auth.system.table.entity.User;
import com.ray.auth.system.table.entity.Work;
import com.ray.sso.SSOCommonValue;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.error.MessageHandle;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.util.Md5Util;
import com.zjhc.flyhong.redis.DefaultRedisService;
import com.zjhc.shiro.captcha.DreamCaptcha;
import com.zjhc.shiro.login.ShiroLogin;
import com.zjhc.web.util.ContextHolderUtils;

/**
 * <h1>用户登录 控制器</h1>
 * 
 * @创建人 ray
 * @创建时间 2017-06-12
 * @版本 1.0
 * @重要修改备注
 * 
 */
@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private WorkService workService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private DreamCaptcha dreamCaptcha;
	@Autowired
	private DefaultRedisService defaultRedisService;

	
	
	/**
	 * @param userName
	 * @param passWord
	 * @return
	 */
	@RequestMapping(value = "ssoLogin")
	public ModelAndView doSsoLogin(HttpServletRequest rquest, HttpServletResponse respose,
			ModelAndView modelAndView) {
		//session 存在 不用登录--->调用登录方法必须校验
		LoginUser loginUser = null;
		//登录ssoSessionId;
		String ssoSessionid = rquest.getParameter("ssoSessionId");
		//登录用户
		String userName = rquest.getParameter("userName");
		//秘钥
		String token = rquest.getParameter("token");
		//单点登录状态
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		
		//不开启的时候
		if(!ssoStatus){
			modelAndView.setViewName("login");
			return modelAndView;
		}
		
		//session校验
		if(StrUtil.isBlank(ssoSessionid)){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
		
         if(StrUtil.isBlank(userName)){
        	String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
		}
       
         
       //token校验
 		if(StrUtil.isBlank(token)){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
 		
 		//校验token 是否允许
 		String ssoKey = MessageHandle.getMsgByKey("sso.key");
 		
 		if(!StrUtil.equals(token, Md5Util.getMd5(ssoKey+ssoSessionid))){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
 		
 		//sso校验
 		String code = defaultRedisService.get(SSOCommonValue.SSO_SESSION_ID+"_"+ssoSessionid);
 		if(StrUtil.isBlank(code)){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
 		
 		
     	ShiroLogin login = new ShiroLogin();
     	//校验本地权限
     	boolean loginStatus  = login.doSsologin(userName, ssoSessionid);
     	if(loginStatus){
			 loginUser = new LoginUser();
				// 获取用户信息
				User user = userService.queryUser(userName);
				if (ObjectUtil.isNotNull(user)) {
					loginUser.setExtendUser(user);
					loginUser.setUserName(user.getUserName());
					loginUser.setLoginName(userName);
					loginUser.setUserId(user.getUserId());
					//超级管理员
					if(StrUtil.equals(user.getManagerType(), ManagerType.SUPER.getType())){
						loginUser.setSuperManager(true);
					}
					//超级管理员
					if(StrUtil.equals(user.getUserType(), UserType.MANAGER.getType())){
						loginUser.setManager(true);
					}
					
					// 获取部门信息
					Organization dept = organizationService.queryOrgByOrgCode(user.getOrgCode());
					if (ObjectUtil.isNotNull(dept)) {
						loginUser.setDeptCode(dept.getOrgId());
						loginUser.setDeptName(dept.getOrgName());
					}
					// 获取所属组织信息
					Organization org = organizationService.queryOrgByTenantId(user.getTenantId());
					if (ObjectUtil.isNotNull(org)) {
						loginUser.setOrgCode(org.getOrgId());
						loginUser.setOrgName(org.getOrgName());
						loginUser.setTenantId(org.getTenantId());
					}
				}
		}else{
			
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
     
		// 信息放入session
		ContextHolderUtils.setLoginUser(loginUser);
		List<TreeNode> menus = menuService.queryUserHomeMenu(MessageHandle.getMsgByKey("app.id"),loginUser);
		modelAndView.addObject("menus", menus);
		modelAndView.setViewName("index");
		return modelAndView;
	}
	
	/**
	 * @param userName
	 * @param passWord
	 * @return
	 */
	@RequestMapping(value = "login")
	public ModelAndView doLogin(String userName, String passWord, String captcha,HttpServletRequest rquest, HttpServletResponse respose,
			ModelAndView modelAndView) {
		//session 存在 不用登录--->调用登录方法必须校验
		
		//使用sso登录的时候 取消本地登录
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		if(ssoStatus){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
		
		LoginUser loginUser = null;// ContextHolderUtils.getLoginUser();
		
		if(ObjectUtil.isNull(loginUser)){
			
			if (StrUtil.isEmpty(captcha)) {
				modelAndView.addObject("loginError", "验证码不为空");
				modelAndView.setViewName("login");
				return modelAndView;
		    }
			
			if (!dreamCaptcha.validate(rquest, respose, captcha)) {
				//登录失败
				modelAndView.addObject("loginError", "验证码错误");
				modelAndView.setViewName("login");
				return modelAndView;
		    }
			// 判断是否登录成功
			ShiroLogin login = new ShiroLogin();
			// 判断登录状态
			boolean loginStatus = login.dologin(userName,passWord);
			if(loginStatus){
				 loginUser = new LoginUser();
					// 获取用户信息
					User user = userService.queryUser(userName);
					if (ObjectUtil.isNotNull(user)) {
						loginUser.setExtendUser(user);
						loginUser.setUserName(user.getUserName());
						loginUser.setLoginName(userName);
						loginUser.setUserId(user.getUserId());
						//超级管理员
						if(StrUtil.equals(user.getManagerType(), ManagerType.SUPER.getType())){
							loginUser.setSuperManager(true);
						}
						//超级管理员
						if(StrUtil.equals(user.getUserType(), UserType.MANAGER.getType())){
							loginUser.setManager(true);
						}
						
						// 获取部门信息
						Organization dept = organizationService.queryOrgByOrgCode(user.getOrgCode());
						if (ObjectUtil.isNotNull(dept)) {
							loginUser.setDeptCode(dept.getOrgId());
							loginUser.setDeptName(dept.getOrgName());
						}
						// 获取所属组织信息
						Organization org = organizationService.queryOrgByTenantId(user.getTenantId());
						if (ObjectUtil.isNotNull(org)) {
							loginUser.setOrgCode(org.getOrgId());
							loginUser.setOrgName(org.getOrgName());
							loginUser.setTenantId(org.getTenantId());
						}
					}
			}else{
				//登录失败
				modelAndView.addObject("loginError", "用户或密码不存在");
				modelAndView.setViewName("login");
				return modelAndView;
			}
		}
		//用户部门删除
		if(StrUtil.isBlank(loginUser.getTenantId())){
			//登录失败
			modelAndView.addObject("loginError", "用户所属公司已注销.");
			modelAndView.setViewName("login");
			return modelAndView;
		}
		// 登录时间
		loginUser.setLoginTime(new Date());
		// 信息放入session
		ContextHolderUtils.setLoginUser(loginUser);
		List<TreeNode> menus = menuService.queryUserHomeMenu(MessageHandle.getMsgByKey("app.id"),loginUser);
		modelAndView.addObject("menus", menus);
		//加载个人工作任务
		PageDto<Work> dto = new PageDto<Work>(1, 10, null);
	    dto = workService.queryMyTodoWork(new Work(), dto, loginUser);
	    modelAndView.addObject("works", dto);
	  //加载通知信息
	    PageDto<Notice> noticePagedto = new PageDto<Notice>(1, 10, "CREATE_TIME desc");
	    noticePagedto = noticeService.queryNotice(new Notice(), noticePagedto, loginUser);
	    modelAndView.addObject("notices", noticePagedto);
		modelAndView.setViewName("index");
		return modelAndView;
	}

	
	
	@RequestMapping(value = "index")
	public ModelAndView doIndex(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		LoginUser loginUser = ContextHolderUtils.getLoginUser();
		if (ObjectUtil.isNotNull(loginUser)) {
			List<TreeNode> menus = menuService.queryUserHomeMenu(MessageHandle.getMsgByKey("app.id"),loginUser);
			modelAndView.addObject("menus", menus);
			//加载个人工作任务
			PageDto<Work> dto = new PageDto<Work>(1, 10, null);
		    dto = workService.queryMyTodoWork(new Work(), dto, loginUser);
		    modelAndView.addObject("works", dto);
		  //加载通知信息
		    PageDto<Notice> noticePagedto = new PageDto<Notice>(1, 10, "CREATE_TIME desc");
		    noticePagedto = noticeService.queryNotice(new Notice(), noticePagedto, loginUser);
		    modelAndView.addObject("notices", noticePagedto);
			modelAndView.setViewName("index");
			return modelAndView;
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	

	@RequestMapping(value = "view")
	public ModelAndView doView(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		//使用sso登录的时候 取消本地登录
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		
		if(ssoStatus){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping(value = "logout")
	public ModelAndView logout(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		 Subject subject = SecurityUtils.getSubject();  
	    if (subject.isAuthenticated()) {  
	        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存  
	    }  
	    //使用sso登录的时候 取消本地登录
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		if(ssoStatus){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			loginUrl+="&logout=logout";
			return new ModelAndView("redirect:"+loginUrl);
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping(value = "main")
	public String doMain(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		return "main";
	}

}
